<?php
/**
 * XGPHP 轻量级PHP框架
 * @link http://xgphp.xg3.cn
 * @version 2.0.0
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author 讯高科技 <xungaokeji@qq.com>
*/
namespace xg\response;
use \xg\facade\View;
use \xg\facade\Request;
use \helper\Arr;

class Result extends Json {
	protected $isJson = false;

	public function isJson($isJson = true) {
		$this->isJson = $isJson;
		return $this;
	}
	
	public function success(string $message,$goto=null) {
		return $this->result($message,$goto,1);
	}
	
	public function message(string $message,$goto=null) {
		return $this->result($message,$goto,0);
	}
	
	public function error(string $message,$goto=null) {
		return $this->result($message,$goto,-1);
	}
	
	public function result() {
		$args=func_get_args();
		$data=[];
		foreach($args as $info){
			if(is_numeric($info)){
				$data['code']=intval($info);
			}elseif(is_array($info)){
				$data=Arr::extend($data,$info);
			}elseif(is_string($info)){
				if(!isset($data['message'])){
					$data['message']=$info;
				}else{
					$data['goto']=$info;
				}
			}
		}
		if(!$data){
			$data=['code'=>0];
		}elseif(!isset($data['code'])){
			$data['code']=0;
		}
		return $this->content($data);
	}
	
	protected function output() {
		$data = $this->content;
		if (Request::isAjax() or $this->isJson) {
			$this->contentType('application/json');
			$data = json_encode($data, $this->json_encode_options);
		} else {
			$this->contentType('text/html');
			if (is_array($data)) {
				$data = View::fetch('',$data);
			}
		}
		return $data;
	}
}
?>